package liuhe.http;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import liuhe.manager.TianziManager;
import liuhe.tools.Common;

public class TianziHttp {
	
	
	CloseableHttpClient httpClient = null;
	RequestConfig requestConfig = null;
	HttpClientContext clientContext = null;
	
	public long canLoginTime;
	WebDriver driver = null;

	int defaultTimeout = 30*1000;
	
	 {

		 
		 
	    requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
	    requestConfig = RequestConfig.copy(requestConfig).setRedirectsEnabled(false).build();//��ֹ�ض��� �� �Ա��ȡcookieb18
	    requestConfig = RequestConfig.copy(requestConfig).setConnectTimeout(defaultTimeout).setConnectionRequestTimeout(defaultTimeout).setSocketTimeout(defaultTimeout).build();//���ó�ʱ
	    httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
	 }
		
	String withoutMemberServiceCookie = "";
	
	String withMenberService = "";
	
	Map<String, String> myCookies = new HashMap<String, String>();
	
	String ADDRESS = "https://www.ps3838.com/";
	
	String ACCOUNT = "004Z000006";
	String PWD = "aaaa2345";
	String SC = "";
	
	
	int grabEventsfailtimes = 0;
	
	long loginTime = 0L;
	
    //-1 ���״̬  ,  1��¼�ɹ�  2ץȡ�ɹ�
    int statusCode = -1;
	
    public  void setLoginParams(String address, String account, String pwd,String sc){
		
			ADDRESS = address;
			ACCOUNT = account;
			PWD = pwd;
			SC = sc;
			
	}
    
    public int getStatusCode() {

   	 return statusCode;
    }
    
    
	public long getCanLoginTime() {
      	return canLoginTime;
    }
    
    public void updateStatusCode(int i) {

   	 if(i!= 3) {
   		System.out.println(ACCOUNT + ": update ps38_statusCode from " +   Integer.toString(statusCode) + " to " + Integer.toString(i));
   	 }
   	 
   	 if(i == -3) {
   		grabEventsfailtimes++;
   	 }
   	 
   	 if(i ==3) {
   		grabEventsfailtimes = 0;
   	 }
   	 
   	 if(grabEventsfailtimes > 10) {
   		 
   		grabEventsfailtimes = 0;
   		 
   		 System.out.println("grab failed times big than 10 need relogin");
   		 
   		 i = -1;
   	 }
   	 
   	 statusCode = i;
    }
    
    
    public String getAccount() {
    	return ACCOUNT;
    }
	
    public void login() {
    	
    	driver = new ChromeDriver(); 
    	
    	try {

            driver.manage().window().maximize();
            driver.get(ADDRESS);

            
            // ʹ����ʽ�ȴ���ȷ�� id="code" ��Ԫ�ؼ������
            WebDriverWait wait = new WebDriverWait(driver, 30); // ��ȴ� 10 ��
            WebElement codeElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("code")));            
            codeElement.sendKeys(SC); // �滻Ϊʵ��ֵ
            Thread.sleep(2000);

            WebElement wb = driver.findElements(By.className("btn-enter")).get(1);
            wb.click();

            Thread.sleep(2000);
            
            boolean isElementPresent = !driver.findElements(By.id("modalBtnConfirm")).isEmpty();
            if (isElementPresent) {
                System.out.println("Element with id 'modalBtnConfirm' is present.");
                driver.findElement(By.id("modalBtnConfirm")).click();
            } else {
                System.out.println("Element with id 'modalBtnConfirm' is not present.");
            }
            
            Thread.sleep(6000);

            String originalHandle = driver.getWindowHandle(); // ��ȡ��ǰ���ھ��

            for (String handle : driver.getWindowHandles()) {
                driver.switchTo().window(handle); // �л�������
                try {
                    WebElement element = driver.findElement(By.id("valid")); // ���Բ���Ԫ��
                    System.out.println("Element found in window: " + driver.getTitle());
                    originalHandle = handle;
                    break;
                } catch (Exception e) {
                    System.out.println("Element not found in window: " + driver.getTitle());
                }
            }
            // �л���ԭʼ���ڣ������Ҫ��
            driver.switchTo().window(originalHandle);
            boolean loginSuccess = false;
            int tryTimes = 0;
            while(loginSuccess==false&&tryTimes<40) {
                WebElement imgElement = driver.findElement(By.id("valid"));                
                String code = getPicNum(imgElement);
                if(code!=null&&code.matches("^\\d{4}$")) {
                	driver.findElement(By.id("txtusername")).sendKeys(ACCOUNT);
                	driver.findElement(By.id("txtuserpassword")).sendKeys(PWD);
                	driver.findElement(By.id("txtsn")).sendKeys(code);
                	driver.findElement(By.id("btn-login")).click();        	
                	Thread.sleep(6000);
                	if(driver.getPageSource().contains("报表查询"));
                	{
                		loginSuccess= true;
                		updateStatusCode(1);
                        Set<Cookie> cookies = driver.manage().getCookies();

                        for(Cookie cookie: cookies) {            	 
                        	myCookies.put(cookie.getName(), cookie.getValue());
                        }
                        
                        
                        
                        
                        try {
                            // 3. 显式等待模态框出现（最多等待10秒）
                            WebDriverWait wait1 = new WebDriverWait(driver, 10);
                            
                            // 4. 检查并获取模态框元素
                            WebElement modalDialog = wait1.until(ExpectedConditions.presenceOfElementLocated(
                                By.cssSelector("div.modal-dialog")
                            ));
                            
                            Thread.sleep(2000);

                            // 5. 在模态框内部定位确定按钮
                            WebElement confirmButton = modalDialog.findElement(By.xpath("//button[@data-bb-handler='ok']"));
                            

                            // 6. 点击确定按钮
                            confirmButton.click();

                            // 7. 可选：等待模态框消失
                            wait.until(ExpectedConditions.invisibilityOf(modalDialog));
                        }catch(Exception e) {
                        	e.printStackTrace();
                        }
                        
                        

                        
                        
                        
                        
                        
                        driver.findElement(By.id("m1")).click();
                        Thread.sleep(2000);
                		Common.logOut(ACCOUNT + "tianzi login success");
                		return;
                	}
                }else {
                	driver.findElement(By.id("valid")).click();  
                	Thread.sleep(1000);
                }
                Thread.sleep(2000);
                tryTimes++;
            }
            
            if(loginSuccess==false) {
            	driver.quit();
            	updateStatusCode(-1);
            }

    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	driver.quit();
    	updateStatusCode(-1);

    	
    }
    
    
    public String getPicNum(WebElement imgElement) {
    	try {
            // ��ȡ src ���Ե�ֵ
            String imgSrc = imgElement.getAttribute("src");
            
            
            String base64Data = imgSrc.split(",")[1];
            
            // ���� Base64 �ַ���Ϊ�ֽ�����
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);
            
            File storeFile = new File(ACCOUNT+"tianzi.png");   //ͼƬ���浽��ǰλ��
            FileOutputStream output = new FileOutputStream(storeFile);  

            output.write(imageBytes);  
            output.close();  
            
            String url = "http://103.234.98.153:8089/api/tr-run/";
            File file = new File(ACCOUNT+"tianzi.png");

            HttpPost httpPost = new HttpPost(url);

            // ����MultipartEntityBuilder�������ಿ�ֱ�����
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addPart("file", new FileBody(file));  // �ϴ��ļ�
            builder.addPart("compress", new StringBody("0"));  // ����������

            // ����������
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            // ִ�����󲢻�ȡ��Ӧ

            CloseableHttpResponse response = httpClient.execute(httpPost);
            // ��ȡ��Ӧ�岢ת��Ϊ�ַ���
            String responseString = EntityUtils.toString(response.getEntity());

            // �����Ӧ����
            
            
            if(responseString.contains("raw_out")) {
                ObjectMapper objectMapper = new ObjectMapper();

                // �� JSON �ַ�������Ϊ JsonNode
                JsonNode rootNode = objectMapper.readTree(responseString);

                // ��ȡ "data" �ڵ�
                JsonNode dataNode = rootNode.path("data");

                // ��ȡ "raw_out" ����
                JsonNode rawOutNode = dataNode.path("raw_out");

                // ��ȡ "raw_out" �����еĵ�һ��Ԫ��
                JsonNode firstRawOutNode = rawOutNode.get(0);

                // ��ȡ�ڶ���Ԫ�أ��� "1240"��
                String extractedValue = firstRawOutNode.get(1).asText();

                extractedValue = extractedValue.replace("^", "4");
                extractedValue = extractedValue.replace("g", "8");
                extractedValue = extractedValue.replace(">", "7");
                extractedValue = extractedValue.replace(",", "8");
                extractedValue = extractedValue.replace("o", "0");
                extractedValue = extractedValue.replace("Z", "2");
                extractedValue = extractedValue.replace(" ", "");
                
                if (extractedValue.matches("^\\d{4}$")) {                                        
                    return extractedValue;
                } 
            }
            

    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	return "";
    }
    
    
    public void getActualData() {
    	try {
    		
    		driver.findElement(By.id("m1")).click();
    		
    		Thread.sleep(4000);
    		
    		JSONObject currentData = new JSONObject();
    		currentData.put("msg", "FAILED");
    		currentData.put("account", ACCOUNT);
    		
    		String currIssue = driver.findElement(By.id("season-count")).getAttribute("innerHTML");
    		SimpleDateFormat dfyear = new SimpleDateFormat("yyyy");
    		String year = dfyear.format(System.currentTimeMillis());
    		if(currIssue.length()==2) {
    			currIssue = "0" + currIssue;
    		}
    		currIssue = year + currIssue;
    		
            WebElement tbody = driver.findElement(By.id("tbody-monitor-tmz6"));
            
            String html = driver.getPageSource();
            
            JSONArray ja1 = new JSONArray();
            
            // 解析HTML文档
            Document doc = Jsoup.parse(html);

            // 获取所有 tr 元素
            Elements rows = doc.select("tbody#tbody-monitor-tmz6 tr");

            // 遍历 tr 元素，获取所需的数据
            for (Element row : rows) {
            	if(row.toString().contains("无相关记录")) {
        	         
         	         currentData.put("data", ja1);
         	         break;
            	}
                String number = row.select("td.stock span.red, td.stock span.blue, td.stock span.green").text().trim();
                
                // 获取第三列的金额（例如：157223 或 203915）
                String amount = row.select("td:nth-of-type(3)").text().trim();
                
                String risk = row.select("td:nth-of-type(3)").text().trim();
                
                if(!number.matches("^\\d{2}$")) {
                	continue;
                }
                
                JSONObject newItem = new JSONObject();
              newItem.put("amount", Integer.parseInt(amount));
              newItem.put("contents", number);
              newItem.put("earnings", Integer.parseInt(risk));
              ja1.put(newItem);

            }
            
            currentData.put("data", ja1);

            driver.findElement(By.id("m13")).click();
            
            Thread.sleep(4000);
            
            driver.findElement(By.id("m4353")).click();
            
            Thread.sleep(4000);
            
            String html1 = driver.getPageSource();
            
            JSONArray ja2 = new JSONArray();

            // 解析HTML文档
            Document doc1 = Jsoup.parse(html1);
            
            Element t = doc1.select("#table-monitor-other").first();
            
            Element tr = t.select("tbody tr").first();

         // 获取表格
            Element table = tr.select("table.table-report").first();

            // 获取表格中的所有行
            Elements rows1 = table.select("tbody tr");



       
            
            for (Element row : rows1) {
            	if(row.toString().contains("无相关记录")) {
        	         currentData.put("msg", "SUCCESS");
         	         currentData.put("yxdata", ja2);
         	         currentData.put("grabtime", System.currentTimeMillis());
         	         currentData.put("currIssue", currIssue);
         	         currentData.put("currOpenTime", 0);
         	         currentData.put("sellTime", 0);
         	         TianziManager.dataJArray.put(currentData);
         	        Common.logOut((ACCOUNT+ " tianzi ActualData success" ));
            		return;
            	}
            	
            	 // 提取“球号”和“会员下注”列
                String number = row.select("td.stock").text(); // 球号
                if(number.contains(" ")||number.equals("")) {
                	continue;
                }
                String amount = row.select("td:nth-child(3)").text(); // 会员下注
                String risk = "0";

                JSONObject newItem = new JSONObject();
              newItem.put("amount", Integer.parseInt(amount));
              newItem.put("contents", number);
              newItem.put("earnings", Integer.parseInt(risk));
              ja2.put(newItem);

            }
            
            
 	         currentData.put("msg", "SUCCESS");
 	        currentData.put("yxdata", ja2);
 	         currentData.put("grabtime", System.currentTimeMillis());
 	         currentData.put("currIssue", currIssue);
 	         currentData.put("currOpenTime", 0);
 	         currentData.put("sellTime", 0);
 	         TianziManager.dataJArray.put(currentData);
 	        Common.logOut((ACCOUNT+ " tianzi ActualData success" ));
 	        return;
    	}catch(Exception e) {

    		e.printStackTrace();
    	}
    	Common.logOut((ACCOUNT+ " tianzi ActualData failed" ));
    	driver.quit();
    	updateStatusCode(-1);
    }
}
